package com.cskaoyan.service;

import com.cskaoyan.bean.MarketAdmin;
import com.cskaoyan.bean.MarketAdminExample;
import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.mapper.MarketAdminMapper;
import com.cskaoyan.util.MyBatisUtil;
import com.cskaoyan.util.StringUtil;
import com.cskaoyan.util.TransactionUtil;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @Author：LiuFan
 * @Project：first-project
 * @Package：com.cskaoyan.service
 * @Date：2023/5/31 11:52
 */
public class AdminAdminServiceImpl implements AdminAdminService {



    private SqlSessionFactory sqlSessionFactory = MyBatisUtil.getSqlSessionFactory();

    @Override
    public List<MarketAdmin> list(String username, Integer page, Integer limit, String sort, String order) {

        MarketAdminExample example = new MarketAdminExample();
        MarketAdminExample.Criteria criteria = example.createCriteria();
        //接收参数判空
        //可根据管理员名称查找
        if (!StringUtil.isEmpty(username)) {
            criteria.andUsernameLike("%" + username + "%");
        }
        //没有逻辑删除
        criteria.andDeletedEqualTo(false);

        //分类 DESC指的返回结果降序排列
        if (!StringUtil.isEmpty(sort) && !StringUtil.isEmpty(order)) {
            example.setOrderByClause(sort + " " + order);
        }
        PageHelper.startPage(page, limit);
        MarketAdminMapper adminMapper = sqlSessionFactory.openSession().getMapper(MarketAdminMapper.class);
        return adminMapper.selectByExample(example);
    }

    @Override
    public BaseRespVo create(MarketAdmin admin) {
        //1.事务
        TransactionUtil.startTransaction();

        //2.提取参数判空\判断其他不利因素
        BaseRespVo isError = validate(admin);
        //若判断不为null 即有错误（参数为空）
        if (isError != null){
            return isError;
        }

        //3.向数据库更新数据
        //随机密码
        String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        base += "0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 8; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        admin.setPassword(sb.toString());

        this.add(admin);


        TransactionUtil.commit();

        return BaseRespVo.ok(admin);
    }

    @Override
    public BaseRespVo update(MarketAdmin admin) {
        //1.事务
        TransactionUtil.startTransaction();

        //2.提取参数判空\判断其他不利因素
        BaseRespVo isError = validate(admin);
        //若判断不为null 即有错误（参数为空）
        if (isError != null){
            return isError;
        }

        Integer adminId = admin.getId();
        if (adminId == null){
            return BaseRespVo.badArgument();
        }

        Date now = new Date();
        //更新时间
        admin.setUpdateTime(now);
        MarketAdminMapper adminMapper = TransactionUtil.getMapper(MarketAdminMapper.class);
        int update = adminMapper.updateByPrimaryKeySelective(admin);
        if (update == 0){
            return BaseRespVo.fail(852,"更新数据失败");
        }

        TransactionUtil.commit();
        return BaseRespVo.ok();
    }

    @Override
    public BaseRespVo delete(MarketAdmin admin) {
        TransactionUtil.startTransaction();
        Integer id = admin.getId();
        if (id == null){
            return BaseRespVo.badArgument();
        }
        MarketAdminMapper adminMapper = TransactionUtil.getMapper(MarketAdminMapper.class);
        int delete = adminMapper.deleteByPrimaryKey(id);
        if (delete == 0){
            return BaseRespVo.fail(963,"删除失败");
        }
        TransactionUtil.commit();
        return BaseRespVo.ok(admin);
    }

    private int add(MarketAdmin admin) {
        Date now = new Date();
        admin.setAddTime(now);
        admin.setUpdateTime(now);
        MarketAdminMapper adminMapper = TransactionUtil.getMapper(MarketAdminMapper.class);
        return adminMapper.insertSelective(admin);
    }


    private BaseRespVo validate(MarketAdmin admin) {
        String name = admin.getUsername();
        if (StringUtil.isEmpty(name)) {
            return BaseRespVo.badArgument();
        }

        String password = admin.getPassword();
        if (StringUtil.isEmpty(password) || password.length() < 6) {
            return BaseRespVo.fail(456, "管理员密码长度不能小于6");
        }
        return null;
    }
}
